/*
 * CAnimationDB.cpp
 *
 *  Created on: 10.04.2012
 *      Author: Caffeine
 */



#include "CAnimationDB.h"
#include "CAnimation.h"

namespace lampe{
namespace animation{

CAnimationDB::CAnimationDB(irr::scene::ISceneManager*s){
	smgr=s;
}

CAnimationDB::~CAnimationDB(){
	for (irr::u32 i=0;i<list.size();i++)
		list[i]->drop();
	list.clear();
}

irr::u32 CAnimationDB::addAnimation(IAnimation*a){
	if (!a)
		return -1;
	list.push_back((CAnimation*)a);
	a->grab();
	return list.size()-1;
}

irr::u32 CAnimationDB::addAnimation(lampe::String animation_name){
    IAnimation*a=lampe::animation::createSkinnedAnimation(animation_name,smgr);
	irr::u32 index=addAnimation(a);
	a->drop();
	return index;
}

void CAnimationDB::removeAnimationByIndex(irr::u32 index){
	list[index]->drop();
	list.erase(index);
}

void CAnimationDB::removeAnimationByName(lampe::String name){
	irr::s32 index=indexOfByName(name);
	if (index<0)
		return;
	return removeAnimationByIndex(index);
}

irr::s32 CAnimationDB::indexOfByName(lampe::String name){
	for (irr::u32 i=0;i<list.size();i++){
		if (list[i]->getName()==name){
			return i;
		}
	}
	return -1;
}

irr::s32 CAnimationDB::indexOfAnimation(IAnimation*a){
	for (irr::u32 i=0;i<list.size();i++)
		if (list[i]==a)
			return i;
	return -1;
}

IAnimation*CAnimationDB::getByIndex(irr::u32 index){
	if (index>=list.size())
		return 0;
	return (IAnimation*)list[index];
}

IAnimation*CAnimationDB::getByName(lampe::String name){
	irr::s32 index=indexOfByName(name);
	if (index<0){
		return 0;
	}
	return getByIndex(index);
}

void CAnimationDB::useFor(lampe::String group,lampe::String name,irr::scene::IAnimatedMeshSceneNode*node){
	IAnimation*a=getByName(group);
	if (!a)
		return;
	a->useFor(name,node);
}

IAnimationDB*defaultAnimationDB=0;

extern void setDefaultAnimationDB(IAnimationDB*db){
	if (defaultAnimationDB)
		defaultAnimationDB->drop();
	defaultAnimationDB=db;
	if (defaultAnimationDB)
		defaultAnimationDB->grab();
}
extern IAnimationDB* getDefaultAnimationDB(){
	return defaultAnimationDB;
}

}//namespace animation
}//namespace irr
